<template>
  <div
    class="city-with-weather"
    @click="handleUpdate(city)"
    @touchstart.stop="handleTouch"
    @touchend.stop="handleTouch"
  >
    <div
      ref="elem"
      class="content-container"
      :class="{'open':isOpen}"
      :tabindex="city.adcode"
      @blur="handleClose"
    >
      <i class="weather-icon" :style="{backgroundImage:`url('${icon}')`}"></i>
      <span class="city-name">{{city.name}}</span>
      <span class="temp">{{city.temperature}}°</span>
      <div class="delete-btn" @click.stop="handleDelete(city)">删除</div>
    </div>
  </div>
</template>

<script>
import { textToCode, getWeatherObj } from '@/tools'

export default {
  name: 'city-with-weather',
  props: {
    city: {
      type: Object
    },
    handleUpdate: Function,
    handleDelete: Function
  },
  computed: {
    icon() {
      return getWeatherObj(textToCode(this.city.weather)).icon
    }
  },
  data: () => ({
    posStart: { x: 0, y: 0 },
    posEnd: { x: 0, y: 0 },
    isOpen: false,
    del: false
  }),
  methods: {
    handleTouch(e) {
      /**
       * 这里使用到'focus',blur'事件,是为了当状态为展开,但没有手动关闭,而是点击其他的元素时,也可以实现关闭的效果
       * 一般的元素没有'focus'事件,但是添加'tabindex'属性后,则可以使用这两个事件
       */
      this.$refs.elem.focus()
      const type = e.type
      const { clientX, clientY } = e.changedTouches[0]
      this[type === 'touchstart' ? 'posStart' : 'posEnd'] = { x: clientX, y: clientY }
      if (
        type === 'touchend' &&
        Math.abs(this.posEnd.y - this.posStart.y) < 40 &&
        Math.abs(this.posEnd.x - this.posStart.x) > 100 &&
        this.city.adcode !== 110100 // 默认的城市不能删除
      ) {
        this.isOpen = this.posEnd.x - this.posStart.x < 0
      }
    },
    handleClose() {
      this.isOpen = false
    }
  }
}
</script>

<style lang="stylus" scoped>
$icon-size = 40px;
$del-size = 3em;

.city-with-weather {
  overflow: hidden;

  .content-container {
    position: relative;
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding: 0 16px;
    transition: all 0.5s;

    &.open {
      transform: translateX(-1 * $del-size);
    }

    &:focus {
      outline: none;
    }
  }

  .weather-icon {
    width: $icon-size;
    height: $icon-size;
    background: center / cover no-repeat;
  }

  .city-name {
    flex: 1;
    margin: 0 10px;
  }

  .temp {
    width: 2em;
    text-align: right;
  }

  .delete-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0;
    right: -1 * $del-size;
    width: $del-size;
    height: 100%;
    color: #ffffff;
    background-color: $error-color;
  }
}
</style>
